package com.ruoyi.system.service.impl;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.UsrUs;
import com.ruoyi.system.mapper.UsrUsMapper;
import com.ruoyi.system.service.IUsrUsService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-30
 */
@Service
public class UsrUsServiceImpl implements IUsrUsService 
{
    @Autowired
    private UsrUsMapper usrUsMapper;

    @Value("${pro.profile:}")
    private String profile;

    /**
     * 查询用户
     * 
     * @param id 用户主键
     * @return 用户
     */
    @Override
    public UsrUs selectUsrUsById(Long id)
    {
        return usrUsMapper.selectUsrUsById(id);
    }

    /**
     * 查询用户列表
     * 
     * @param usrUs 用户
     * @return 用户
     */
    @Override
    public List<UsrUs> selectUsrUsList(UsrUs usrUs)
    {
        return usrUsMapper.selectUsrUsList(usrUs);
    }

    /**
     * 新增用户
     * 
     * @param usrUs 用户
     * @return 结果
     */
    @Override
    public int insertUsrUs(UsrUs usrUs)
    {
        return usrUsMapper.insertUsrUs(usrUs);
    }

    /**
     * 修改用户
     * 
     * @param usrUs 用户
     * @return 结果
     */
    @Override
    public int updateUsrUs(UsrUs usrUs)
    {
        return usrUsMapper.updateUsrUs(usrUs);
    }

    /**
     * 批量删除用户
     * 
     * @param ids 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteUsrUsByIds(Long[] ids)
    {
        return usrUsMapper.deleteUsrUsByIds(ids);
    }

    /**
     * 删除用户信息
     * 
     * @param id 用户主键
     * @return 结果
     */
    @Override
    public int deleteUsrUsById(Long id)
    {
        UsrUs usrUs = usrUsMapper.selectUsrUsById(id);
        if (usrUs != null && usrUs.getImgurl() != null && !usrUs.getImgurl().isEmpty()) {
            String imgurl = usrUs.getImgurl();
            // 从URL中提取文件名
            String fileName = imgurl.substring(imgurl.lastIndexOf("/") + 1);
            String imagePath = "D:\\test\\" + fileName;

            // 删除图片文件
            File imageFile = new File(imagePath);
            if (imageFile.exists()) {
                imageFile.delete();
            }
        }
        return usrUsMapper.deleteUsrUsById(id);
    }

    @Override
    public AjaxResult importData(MultipartFile file, boolean updateSupport) {
        System.out.println("上传题库");
        // 检查上传的文件是否为空，如果为空，返回错误提示
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        // 获取上传文件的原始文件名
        String fileName = file.getOriginalFilename();
        System.out.println("=================" + fileName);
        // 检查文件名是否为空，以及文件后缀是否为.xls 或.xlsx，不满足条件则返回错误提示
        if (fileName == null || (!fileName.endsWith(".xls") &&!fileName.endsWith(".xlsx"))) {
            return AjaxResult.error("请上传后缀名为.xls或.xlsx的文件");
        }
        // 创建一个集合用于存储从 Excel 解析出的 QuestionBank 对象

        try {
            Workbook workbook;
            // 根据文件后缀判断使用 HSSFWorkbook 还是 XSSFWorkbook 来创建 Workbook 对象
            if (fileName.endsWith(".xls")) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else {
                workbook = new XSSFWorkbook(file.getInputStream());
            }
            // 获取 Excel 的第一个工作表
            List<UsrUs> usrUsList = new ArrayList<>();

            int sheetsize = workbook.getNumberOfSheets();
            for (int j = 0; j < sheetsize; j++) {
                Sheet sheet = workbook.getSheetAt(j);
                Map<String, byte[]> imageMap = new HashMap<>();
                if (workbook instanceof HSSFWorkbook) {
                    // 处理.xls文件中的图片（不使用ExcelUtil）
                    HSSFSheet hssfSheet = (HSSFSheet) sheet;
                    //HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook;
                    if (hssfSheet.getDrawingPatriarch() != null) {
                        for (HSSFShape shape : hssfSheet.getDrawingPatriarch().getChildren()) {
                            if (shape instanceof HSSFPicture) {
                                HSSFPicture picture = (HSSFPicture) shape;
                                HSSFClientAnchor anchor = picture.getPreferredSize();
                                String position = anchor.getRow1() + "_" + anchor.getCol1();
                                HSSFPictureData pictureData = picture.getPictureData();
                                imageMap.put(position, pictureData.getData());
                            }
                        }
                    }
                } else {
                    // 处理.xlsx文件中的图片（不使用ExcelUtil）
                    XSSFSheet xssfSheet = (XSSFSheet) sheet;
                    //XSSFWorkbook xssfWorkbook = (XSSFWorkbook) workbook;

                    for (POIXMLDocumentPart part : xssfSheet.getRelations()) {
                        if (part instanceof XSSFDrawing) {
                            XSSFDrawing drawing = (XSSFDrawing) part;
                            for (XSSFShape shape : drawing.getShapes()) {
                                if (shape instanceof XSSFPicture) {
                                    XSSFPicture picture = (XSSFPicture) shape;
                                    XSSFClientAnchor anchor = picture.getPreferredSize();
                                    String position = anchor.getRow1() + "_" + anchor.getCol1();
                                    XSSFPictureData pictureData = picture.getPictureData();
                                    imageMap.put(position, pictureData.getData());
                                }
                            }
                        }
                    }
                }
                int rowNum = sheet.getLastRowNum();
                for (int i = 0; i <= rowNum; i++){
                    UsrUs usrUs = new UsrUs();
                    Row row = sheet.getRow(i);
                    if (row == null){
                        continue;
                    }
                    // 处理name字段
                    int a=0;
                    Cell nameCell = row.getCell(a);
                    while (nameCell == null){
                        a++;
                        nameCell = row.getCell(a);
                    }
                    if (nameCell != null) {
                        if (nameCell.getCellType() == CellType.NUMERIC) {
                            usrUs.setName(String.valueOf((long) nameCell.getNumericCellValue()));
                        } else {
                            usrUs.setName(nameCell.getStringCellValue());
                        }
                    }
                    // 处理age字段
                    Cell ageCell = row.getCell(a+1);
                    if (ageCell != null) {
                        if (ageCell.getCellType() == CellType.NUMERIC) {
                            usrUs.setAge((long) ageCell.getNumericCellValue());
                        } else {
                            usrUs.setAge(Long.valueOf(ageCell.getStringCellValue()));
                        }
                    }
                    // 处理nickname字段
                    Cell nicknameCell = row.getCell(a+2);
                    if (nicknameCell != null) {
                        if (nicknameCell.getCellType() == CellType.NUMERIC) {
                            usrUs.setNickname(String.valueOf((long) nicknameCell.getNumericCellValue()));
                        } else {
                            usrUs.setNickname(nicknameCell.getStringCellValue());
                        }
                    }
                    //获取图片并生成时间戳作为图片路径存储到D:\\test\\时间戳.png

                    String imgurl = null;
                    // 构造图片在Excel中的位置标识（行_列）
                    int picRow = a+3;
                    String picPosition = i + "_" + picRow; // 第i行第4列（从0开始计数）
                    byte[] imageBytes = imageMap.get(picPosition);
                    if (imageBytes != null) {
                        // 生成时间戳作为文件名
                        long timestamp = System.currentTimeMillis();
                        String imageSavePath = "D:\\test\\" + timestamp + ".png";
                        // 保存图片到指定路径
                        try {
                            FileOutputStream fos = new FileOutputStream(imageSavePath);
                            fos.write(imageBytes);
                            fos.close();
                            imgurl = profile + timestamp + ".png";
                            usrUs.setImgurl(imgurl);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    usrUsList.add(usrUs);
                }

            }
            usrUsMapper.insertAll(usrUsList);
        }
        catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.error("文件上传失败，请稍后再试");
            }

        return null;
    }
    public void exportWord(HttpServletResponse response, UsrUs param) {
        System.out.println("param:"+param);
        try {
            XWPFDocument document = new XWPFDocument();
            // 创建表格
            XWPFTable table = document.createTable();
            // 创建表头
            XWPFTableRow headerRow = table.getRow(0);
            headerRow.getCell(0).setText("ID");
            headerRow.addNewTableCell().setText("姓名");
            headerRow.addNewTableCell().setText("年龄");
            headerRow.addNewTableCell().setText("昵称");
            headerRow.addNewTableCell().setText("图片");

            // 添加数据行
            List<UsrUs> users = this.selectUsrUsList(param);
            for (UsrUs user : users) {
                XWPFTableRow row = table.createRow();
                row.getCell(0).setText(String.valueOf(user.getId()));
                row.getCell(1).setText(user.getName());
                row.getCell(2).setText(String.valueOf(user.getAge()));
                row.getCell(3).setText(user.getNickname());
                String imgurl = user.getImgurl();
                if (imgurl != null && !imgurl.isEmpty()) {
                    try {
                        // 从网址下载图片
                        byte[] imageBytes = com.ruoyi.common.utils.file.ImageUtils.readFile(imgurl);
                        if (imageBytes != null) {
                            // 创建段落并插入图片
                            XWPFParagraph imageParagraph = row.getCell(4).addParagraph();
                            XWPFRun imageRun = imageParagraph.createRun();

                            // 判断图片类型
                            String fileExtension = imgurl.substring(imgurl.lastIndexOf(".") + 1).toLowerCase();
                            int imageType;
                            if ("jpg".equals(fileExtension) || "jpeg".equals(fileExtension)) {
                                imageType = XWPFDocument.PICTURE_TYPE_JPEG;
                            } else if ("png".equals(fileExtension)) {
                                imageType = XWPFDocument.PICTURE_TYPE_PNG;
                            } else if ("gif".equals(fileExtension)) {
                                imageType = XWPFDocument.PICTURE_TYPE_GIF;
                            } else {
                                imageType = XWPFDocument.PICTURE_TYPE_JPEG; // 默认JPEG
                            }

                            // 插入图片，设置大小为100x100像素
                            imageRun.addPicture(
                                    new java.io.ByteArrayInputStream(imageBytes),
                                    imageType,
                                    "image." + fileExtension,
                                    org.apache.poi.util.Units.toEMU(100),
                                    org.apache.poi.util.Units.toEMU(100)
                            );
                        } else {
                            // 图片下载失败，显示网址
                            row.getCell(4).setText(imgurl);
                        }
                    } catch (Exception e) {
                        // 出现异常，显示网址和错误信息
                        row.getCell(4).setText("图片加载失败: " + imgurl);
                    }
                } else {
                    // 没有图片网址
                    row.getCell(4).setText("无图片");
                }
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=users.docx");
            // 写入响应
            document.write(response.getOutputStream());
            document.close();
        } catch (Exception e) {
            // 错误处理
        }

    }
    public void exportPdf(HttpServletResponse response, UsrUs param) {
        System.out.println("param:" + param);
        try {
            // 设置响应头
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=users.pdf");

            PdfWriter writer = new PdfWriter(response.getOutputStream());
            PdfDocument pdf = new PdfDocument(writer);
            Document document = new Document(pdf);


            float[] columnWidths = {1, 2, 2, 2, 2};
            com.itextpdf.layout.element.Table table = new com.itextpdf.layout.element.Table(columnWidths);

            // 添加表头
            table.addHeaderCell("ID");
            table.addHeaderCell("姓名");
            table.addHeaderCell("年龄");
            table.addHeaderCell("昵称");
            table.addHeaderCell("图片");

            List<UsrUs> users = this.selectUsrUsList(param);
            for (UsrUs user : users) {
                table.addCell(String.valueOf(user.getId()));
                table.addCell(user.getName());
                table.addCell(String.valueOf(user.getAge()));
                table.addCell(user.getNickname());
                String imgurl = user.getImgurl();
                if (imgurl != null && !imgurl.isEmpty()) {
                    try {
                        // 从网址读取图片
                        byte[] imageBytes = com.ruoyi.common.utils.file.ImageUtils.readFile(imgurl);
                        if (imageBytes != null) {
                            // 创建iText7图片对象
                            ImageData imageData = ImageDataFactory.create(imageBytes);
                            Image image = new Image(imageData);

                            // 设置图片大小
                            image.setWidth(50);
                            image.setHeight(50);

                            // 创建单元格并添加图片
                            com.itextpdf.layout.element.Cell cell = new com.itextpdf.layout.element.Cell();
                            cell.add(image);
                            //cell.setWidth(60); // 设置单元格宽度
                            table.addCell(cell);
                        } else {
                            table.addCell("图片加载失败");
                        }
                    } catch (Exception e) {
                        table.addCell("图片加载失败: " + imgurl);
                    }
                }
                else {
                    table.addCell("无图片");
                }
            }
            // 将表格添加到文档
            document.add(table);
            // 关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportexcel(HttpServletResponse response, UsrUs usrUs) {
        try {
            List<UsrUs> list = this.selectUsrUsList(usrUs);

            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("用户数据");

            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            headerStyle.setFont(font);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"ID", "姓名", "年龄", "昵称", "图片URL"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据
            int rowNum = 1;
            for (UsrUs user : list) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(user.getId() != null ? user.getId() : 0);
                row.createCell(1).setCellValue(user.getName() != null ? user.getName() : "");
                row.createCell(2).setCellValue(user.getAge() != null ? user.getAge() : 0);
                row.createCell(3).setCellValue(user.getNickname() != null ? user.getNickname() : "");
                if (user.getImgurl() != null && !user.getImgurl().isEmpty()) {
                    String imgurl = user.getImgurl();
                    try {
                        byte[] imageBytes = com.ruoyi.common.utils.file.ImageUtils.readFile(imgurl);
                        if (imageBytes != null) {
                            // 创建客户端锚点（图片位置）
                            Drawing<?> drawing = sheet.createDrawingPatriarch();
                            ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
                            anchor.setCol1(4); // 第5列（图片列）
                            anchor.setRow1(rowNum - 1); // 当前行
                            anchor.setCol2(5); // 结束列
                            anchor.setRow2(rowNum); // 结束行

                            // 确定图片类型
                            int pictureType = Workbook.PICTURE_TYPE_JPEG;
                            String fileExtension = imgurl.substring(imgurl.lastIndexOf(".") + 1).toLowerCase();
                            if ("png".equals(fileExtension)) {
                                pictureType = Workbook.PICTURE_TYPE_PNG;
                            }
                            // 创建图片
                            int pictureIdx = workbook.addPicture(imageBytes, pictureType);
                            Picture pict = drawing.createPicture(anchor, pictureIdx);
                            pict.resize(0.8, 0.8); // 调整图片大小
                        } else {
                            row.createCell(4).setCellValue("图片加载失败");
                        }
                    }catch (Exception e){
                        row.createCell(4).setCellValue("图片加载失败");
                    }
                }
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");

            // 写入响应输出流
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
